﻿using System;
using OnlineJudge;
using fastCSharp;
using fastCSharp.diagnostics;

namespace OnlineJudgeServer
{
    /// <summary>
    /// OJ服务
    /// </summary>
    class console : fastCSharp.diagnostics.consoleLog
    {
        /// <summary>
        /// TCP服务调用配置
        /// </summary>
        private static readonly fastCSharp.code.cSharp.tcpServer ojAttribute = ServerIp.GetTcpServer(typeof(OnlineJudge.Server), "OJServer");
        /// <summary>
        /// OJ服务实例
        /// </summary>
        private OnlineJudge.Server.tcpServer server;
        /// <summary>
        /// 当前进程是否正在尝试忽略OJ服务端操作
        /// </summary>
        private bool isTryIgnoreServer;
        /// <summary>
        /// 是否自动设置进程复制重启
        /// </summary>
        protected override bool isSetProcessCopy
        {
            get { return false; }
        }
        /// <summary>
        /// 启动OJ服务
        /// </summary>
        protected override void start()
        {
            Console.WriteLine(ojAttribute.Host);
            isTryIgnoreServer = true;
            try
            {
                if (fastCSharp.config.pub.IsConfigName("OnlineJudge.IgnoreGroup")) OnlineJudgeClient.TcpClient.OJIgnoreGroup();
            }
            catch (Exception error)
            {
                output(error);
            }
            finally
            {
                isTryIgnoreServer = false;
                oj();
            }
        }
        /// <summary>
        /// 启动OJ服务
        /// </summary>
        private void oj()
        {
            try
            {
                if ((server = new OnlineJudge.Server.tcpServer(ojAttribute)).Start())
                {
                    setTcpIgnoreGroup(() => server, () => isTryIgnoreServer);
                    output("OJ服务启动成功");
                    return;
                }
            }
            catch (Exception error)
            {
                output(error);
            }
            server = null;
            output("OJ服务启动失败");
            fastCSharp.threading.timerTask.Default.Add(oj, date.NowSecond.AddSeconds(1));
        }
        /// <summary>
        /// 关闭HTTP服务
        /// </summary>
        protected override void dispose()
        {
            pub.Dispose(ref server);
        }
    }
}
